package org.example.codesandbox.utils;

import org.example.codesandbox.model.ProcessMessage;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.InputStreamReader;

//处理进程获取执行代码的结果
public class ProcessUtils {
    public static ProcessMessage process(Process process, String option) {
        ProcessMessage processMessage = new ProcessMessage();
        StopWatch stopWatch = new StopWatch();
        try {
            stopWatch.start();
            int waitValue = process.waitFor();
            processMessage.setValue(waitValue);
            //返回0说明进程是正常退出
            if (waitValue == 0) {
                System.out.println(option + "成功");
                //得到进程的输入流获取输出信息
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                String readline;
                while ((readline = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(readline);
                }
                processMessage.setMessage(compileOutputStringBuilder.toString());
                System.out.println("输出结果：" + compileOutputStringBuilder.toString());

            } else {
                System.out.println(option + "失败");
                //得到进程的输入流获取输出信息
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                StringBuilder compileOutputStringBuilder = new StringBuilder();
                String readline;
                while ((readline = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(readline);
                }
                processMessage.setMessage(compileOutputStringBuilder.toString());
                //得到进程的输入流获取输出信息
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                StringBuilder errorStringBuilder = new StringBuilder();
                String errorReadline;
                while ((errorReadline = errorReader.readLine()) != null) {
                    errorStringBuilder.append(errorReadline);
                }
                processMessage.setErrorMessage(errorStringBuilder.toString());
                stopWatch.stop();
                processMessage.setTime(stopWatch.getLastTaskTimeMillis());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        stopWatch.stop();
        processMessage.setTime(stopWatch.getLastTaskTimeMillis());

        return processMessage;
    }
}
